package com.fangzhi.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fangzhi.mobel.AdminAccountRoleDeptRelation;
import com.fangzhi.mobel.dto.OrderExcelDto;
import com.fangzhi.mobel.enums.GlobalCodeEnum;
import com.fangzhi.mobel.io.UpdateAfterIo;
import com.fangzhi.mobel.vo.DeptListVo;
import com.fangzhi.mobel.vo.DownloadAfterOrderExcelVo;
import com.fangzhi.mobel.vo.LoginVo;
import com.fangzhi.mobel.vo.RoleListVo;
import com.fangzhi.service.*;
import com.fangzhi.utils.GlobalParam;
import com.fangzhi.utils.ResponseResult;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.nio.file.Files;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/after")
public class AfterController {

    @Autowired
    private OrderAfterService orderAfterService;
    @Autowired
    private AdminAccountRoleDeptRelationService adminAccountRoleDeptRelationService;

    @GetMapping("/afterList")
    public ResponseResult afterList(@RequestParam(defaultValue = "") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate beginTime
                                    , @RequestParam(defaultValue = "") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endTime
                                    , @RequestParam(defaultValue = "") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate beginTimeOrder
                                    , @RequestParam(defaultValue = "") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endTimeOrder
                                    , @RequestParam(defaultValue = "") String orderId
                                    , @RequestParam(defaultValue = "") String hotelName
                                    , @RequestParam(defaultValue = "1") Integer pageNo
                                    , @RequestParam(defaultValue = "20") Integer pageSize){

        return orderAfterService.afterList(orderId, beginTime, endTime, beginTimeOrder, endTimeOrder, hotelName, pageNo, pageSize);
    }

    /**
     * 售后跟进
     * @param io
     * @return
     */
    @PostMapping("/updateAfter")
    public ResponseResult updateAfter(@RequestBody UpdateAfterIo io){
        return orderAfterService.updateAfter(io);
    }

    /**
     * 删除售后订单
     * @param id
     * @return
     */
    @GetMapping("/removeAfter")
    public ResponseResult removeAfter(@RequestParam long id){
        LoginVo loginVo = GlobalParam.LOGIN_ACCOUNT_INFO.get();
        AdminAccountRoleDeptRelation one = adminAccountRoleDeptRelationService.getOne(Wrappers.<AdminAccountRoleDeptRelation>lambdaQuery()
                .eq(AdminAccountRoleDeptRelation::getAdminAccounntId, loginVo.getId()));
        if (one.getRoleId() != 4L)
            return ResponseResult.systemException(GlobalCodeEnum.GL_FAIL_9997);
        boolean b = orderAfterService.removeById(id);
        if (b)
            return ResponseResult.OK();
        throw new RuntimeException("删除售后订单失败" + id);
    }

    /**
     * 下载orders 订单
     * @return
     * @throws IOException
     */
    @GetMapping("/downloadAfterOrderExcel")
    public synchronized ResponseEntity<byte[]> downloadAfterOrderExcel(@RequestParam(defaultValue = "") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startTime
            , @RequestParam(defaultValue = "") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endTime
            , @RequestParam(defaultValue = "") String hotelName) throws IOException {
        LoginVo loginVo = GlobalParam.LOGIN_ACCOUNT_INFO.get();
        if (!Arrays.asList(4,5,6).contains(loginVo.getRoleId()))
            return null;

        List<DownloadAfterOrderExcelVo> voList = orderAfterService.queryAfterOrderExcelList(startTime, endTime, hotelName);
        if (voList.isEmpty())
            return null;

        createExcel(voList);
        String property = System.getProperty("user.dir");
        String resoure = property + "/excel/orderAfterExcelNew.xlsx";
        byte[] fileContent = Files.readAllBytes(new File(resoure).toPath()); // 注意：这种方式适合小文件
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=历史报价表.xlxs");
        headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE);
        return ResponseEntity.ok()
                .headers(headers)
                .body(fileContent);
    }

    public void createExcel(List<DownloadAfterOrderExcelVo> voList) throws IOException {
        String property = System.getProperty("user.dir");
        // 加载Excel模板
        String excelPath = "/excel/order-after.xlsx";
        FileInputStream fileInputStream = new FileInputStream(property + excelPath);
        XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream);
        XSSFSheet sheet = workbook.getSheetAt(0);
        sheet.createFreezePane(0, 1);
        for (int i = 0; i < voList.size(); i++) {
            DownloadAfterOrderExcelVo vo = voList.get(i);
            XSSFRow row = sheet.createRow(1 + i);
            // 时间
            Cell cell = row.createCell(0);
            cell.setCellValue(vo.getTime());
            // 售后类型
            cell = row.createCell(1);
            cell.setCellValue("退货");
            if (vo.getType() == 2){
                cell.setCellValue("换货");
            }else if (vo.getType() == 3){
                cell.setCellValue("补发");
            }
            // 订单号
            cell = row.createCell(2);
            cell.setCellValue(vo.getOrderId());
            // 酒店名字
            cell = row.createCell(3);
            cell.setCellValue(vo.getHotelName());
            // 部门名城
            cell = row.createCell(4);
            cell.setCellValue(vo.getDeptName());
            // 业务员
            cell = row.createCell(5);
            cell.setCellValue(vo.getAccountName());
            // 补缴金额
            cell = row.createCell(6);
            cell.setCellValue(vo.getPrice());
            // 赔付金额
            cell = row.createCell(7);
            cell.setCellValue(vo.getAfterPrice());
            // 图片凭证
            cell = row.createCell(8);
            if (!StringUtils.hasText(vo.getImageCover()))
                continue;
            URL imageUrl = new URL(GlobalParam.IMAGE_URL + vo.getImageCover());
            InputStream imageStream = imageUrl.openStream();
            byte[] bytes = IOUtils.toByteArray(imageStream);
            XSSFDrawing drawing = sheet.createDrawingPatriarch();
            XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, cell.getColumnIndex(), row.getRowNum(), cell.getColumnIndex() + 1, row.getRowNum() + 1);
            int pictureIdx = workbook.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);
            XSSFPicture picture = drawing.createPicture(anchor, pictureIdx);
            picture.resize(1, 1);
            imageStream.close();
            // 提交人
            cell = row.createCell(9);
            cell.setCellValue(vo.getCommitName());
            // 处理人
            cell = row.createCell(10);
            cell.setCellValue(vo.getHandleName());
            // 反馈事项
            cell = row.createCell(11);
            cell.setCellValue(vo.getComments());
            // 问题归属
            cell = row.createCell(12);
            cell.setCellValue(vo.getBelongTo());
            // 处理方案
            cell = row.createCell(13);
            cell.setCellValue(vo.getAction());
            // 退回单号
            cell = row.createCell(14);
            cell.setCellValue(vo.getReturnOrderNumber());
        }
        FileOutputStream fileOutputStream = new FileOutputStream(property + "/excel/orderAfterExcelNew.xlsx");
        workbook.write(fileOutputStream);
        workbook.close();
        fileOutputStream.close();
    }
}
